<template>
    <div class="LogicalRoomCalendar">
        <ItemDetail :loading="tableLoading" :show.sync="showModal" :value="item" :title="`${action} Item`" :id="itemID" @submit="confirmSubmit" :action="action"></ItemDetail>
        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div class="panel-heading" style="overflow: hidden;">
                        Ics Urls
                        <button class="btn btn-primary pull-right" @click="updateIcs" :disabled="updateIcalStatus" style="margin-left: 8px;">Update</button>
                        <button class="btn btn-info pull-right" @click="add">Add</button>
                    </div>
                    <div class="panel-body">
                        <div :key="'url' + index"  v-for="(url, index) in urls" class="external-event" style="position: relative; padding: 5px;"
                             :style="{'background': colors[index] ? colors[index] : '#c0392b'}">
                            <span style="display: inline-block; color: #fff;">{{ url.title }}:</span>
                            <a style="color: #fff;" :href=" url.url" target="_blank">{{ url.url }}</a>
                            <span class="pull-right">
                            <a @click="edit(url)"><i class="fif fif-edit text-white" style="cursor: pointer;color: #fff;"></i></a>&nbsp;
                            <a @click="remove(url)"><i class="fif fif-delete text-red" style="cursor: pointer;"></i></a>
                        </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div class="panel-heading">Logical Room Ical</div>
                    <div>
                        <full-calendar value="airbnb" :events="events" :priceData="priceData"></full-calendar>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import fullCalendar from '@/components/widgets/RoomCalendar/RoomCalendar'
    import ItemDetail from '@/components/widgets/ItemDetail'
    import {getIcsUrls, updateLogicalIcs, addIcs, removeIcs, updateIcs} from '@/api/event'
    import  {searchModel} from "@/api/model";
    import swal from 'sweetalert'
    // utils
    import {l2o} from '@/utils'

    import columns from '@/config/columns'
    export default {
        name: "LogicalRoomCalendar",
        components: {ItemDetail, fullCalendar},
        created() {
            this.colors = [ '#e67e22','#f1c40f','#16a085', '#27ae60', '#2980b9','#8e44ad', '#2c3e50',
                '#95a5a6','#ecf0f1','#f39c12','#7f8c8d', '#d35400', '#c0392b','#e74c3c']
            this.logical_room_id = this.$route.hash.length ? this.$route.params.lid + this.$route.hash : this.$route.params.lid
            this.defaultColumns = columns.IcsUrl
        },
        activated() {
            this.fetch()
        },
        data() {
            return {
                urls: [],
                events: [],
                updateIcalStatus: false,
                priceData: [],
                showModal: false,
                itemID: null,
                item: null,
                action: 'edit',
                tableLoading: false,
            }
        },
        methods: {
            fetch() {

                searchModel("PriceCalendar", {
                    "search_keys": {"physical_room__logical_room__logical_room_id__icontains": this.logical_room_id},
                    "page_size": 99999,
                }).then(res => {
                    this.priceData = res.data.list
                })

                getIcsUrls(this.logical_room_id).then( response => {
                    this.urls = response.data.icses
                    let evt = response.data.icals
                    this.id = response.data.logical_room.id
                    this.events = []
                    for (let i = 0; i < evt.length; i++) {
                        let eventIndex = 0
                        for (let index in this.events) {
                            if (this.events[index].start<=evt[i].check_in_date && this.events[index].end > evt[i].check_in_date) {
                                eventIndex = this.events[index].eventIndex + 1
                            }
                        }

                        let icsIndex = this.getIcsIndex(evt[i].generated_by_id)
                        this.events.push({
                            start: evt[i].check_in_date,
                            end: evt[i].check_out_date,
                            title: evt[i].description,
                            cssStyle: {'background': icsIndex !== null ? this.colors[icsIndex] : '#2980b9','color':'#fff'},
                            eventIndex: eventIndex
                        })
                    }

                })
            },
            getIcsIndex(target) {
                let index = null
                for (let i=0; i<this.urls.length; i++) {
                    if (this.urls[i].id === target) {
                        index = i
                        break
                    }
                }
                return index
            },
            edit(url) {
                this.action = 'edit'
                this.itemID = url.id
                this.origin = url
                let item = []
                let fields = {}
                for (let i = 0; i < this.defaultColumns.length; i++) {
                    fields[this.defaultColumns[i].key] = i
                    item[i] = Object.assign({}, this.defaultColumns[i])
                }

                for (let key in url) {
                    if (key in fields) {
                        let i = fields[key]
                        item[i].value = url[key]
                    }
                }

                this.item = item
                this.showModal = true
            },
            add() {
                this.action = 'add'
                this.itemID = null
                this.item = []
                for (let i=0; i<this.defaultColumns.length; i++) {
                    this.item[i] = Object.assign({}, this.defaultColumns[i])
                }

                this.showModal = true
            },
            remove(url) {
                if (url.id) {
                    swal({
                        title: "Are you sure?",
                        text: "Remove this item",
                        icon: "warning",
                        dangerMode: true,
                        buttons: true,
                    }).then( (willDelete)=> {
                        if (willDelete) {
                            removeIcs(url.id).then( res => {
                                this.handlerResponse(res)
                            }).catch( e =>{
                            } )
                        }
                    } )
                }
            },
            confirmSubmit(action, value) {
                if (!this.id)
                    return
                let attr = l2o(value, 'key')
                if (attr && this.origin) {
                    for (let key in attr) {
                        if (this.origin[key] === attr[key] && action === 'edit') {
                            delete attr[key]
                        } else if (key === 'password' && attr[key] === '') {
                            delete attr[key]
                        }
                    }
                }
                if (attr === null) {
                    attr = {id: this.itemID}
                } else {
                    attr.id = this.itemID
                }

                if (action == 'add') {
                    swal({
                        title: "Are you sure?",
                        text: "Add this item",
                        icon: "warning",
                        dangerMode: true,
                        buttons: true,
                    }).then( (willAdd)=> {
                        if (willAdd) {
                            if ((attr.url.indexOf('.ics') == -1 && attr.url.indexOf('.html') == -1 && attr.url.indexOf('.htm') == -1) ||
                                (attr.url.indexOf('http') == -1 && attr.url.indexOf('http') ==1) ) {
                                swal("Fail", "Require .ics file", "error")
                                return
                            }
                            attr['id'] = this.id
                            attr['color'] = 'bg-primary'
                            addIcs(this.id, attr).then( res => {
                                this.handlerResponse(res)
                            }).catch( e =>{
                            } )
                        }
                    } )
                } else if (action == 'edit') {
                    updateIcs(this.itemID, attr).then(res => {
                        this.handlerResponse(res)
                    }).catch( e => {})
                }
                console.log(attr)
            },
            updateIcs() {
                this.updateIcalStatus = true
                updateLogicalIcs(this.id).then(res => {
                    this.updateIcalStatus = false
                    if (res.data.code == 0) {
                       $.toast({
                           heading: 'Update Success',
                           text: '',
                           position: 'top-right',
                           icon: 'success'
                       })
                    } else {
                        $.toast({
                            heading: 'Update fail',
                            text: '',
                            position: 'top-right',
                            loaderBg: '#ff6849',
                            icon: 'error',
                        });
                    }
                }).catch(e => {
                    this.updateIcalStatus = false
                    console.log(e)
                })
            },
            handlerResponse(res) {
                if (res.data == 'ok') {
                    this.showModal = false
                    this.fetch()
                    swal("Success", "", "success")
                } else {
                    swal("Fail", "", "error")
                }
            },
        }
    }
</script>

<style scoped lang="stylus">
    .external-event
        padding: 5px 10px;
        font-weight: bold;
        margin-bottom: 4px;
        box-shadow: 0 1px 1px rgba(0,0,0,0.1);
        text-shadow: 0 1px 1px rgba(0,0,0,0.1);
        border-radius: 3px;
        cursor: move;
</style>